package com.schoolinfo.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.schoolinfo.dao.GoodsDAO;
import com.schoolinfo.dao.SecondClassDAO;
import com.schoolinfo.model.FirstClass;
import com.schoolinfo.model.Goods;
import com.schoolinfo.model.GoodsPager;
import com.schoolinfo.model.SecondClass;
import com.schoolinfo.model.User;
import com.schoolinfo.util.DigestUtil;
import com.schoolinfo.util.FileUtil;

/**
 * 负责处理所有页面关于商品的请求
 * @author wangjiawen
 *
 */
public class GoodsAction extends ActionSupport {
	private GoodsDAO goodsDAO;
	private SecondClassDAO secondClassDAO;
	private String errorMsg;
	private File picFile;
	private String picFileContentType;
	private String picFileFileName;
	private String type;//1:卖 2：买
	//允许上传文件格式
	private static String ALLOWED_PIC_TYPE="png|bmp|jpeg|jpg|gif";
	
	private String userId;//email
	
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
	
	
	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getPicFileContentType() {
		return picFileContentType;
	}

	public void setPicFileContentType(String picFileContentType) {
		this.picFileContentType = picFileContentType;
	}

	public String getPicFileFileName() {
		return picFileFileName;
	}

	public void setPicFileFileName(String picFileFileName) {
		this.picFileFileName = picFileFileName;
	}

	public File getPicFile() {
		return picFile;
	}

	public void setPicFile(File picFile) {
		this.picFile = picFile;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public SecondClassDAO getSecondClassDAO() {
		return secondClassDAO;
	}

	public void setSecondClassDAO(SecondClassDAO secondClassDAO) {
		this.secondClassDAO = secondClassDAO;
	}

	private int id;
	private int secondId;
	
	private int offset;
	private String keyWords;
	
	private Goods goods;
	
	public Goods getGoods() {
		return goods;
	}

	public void setGoods(Goods goods) {
		this.goods = goods;
	}

	public String getKeyWords() {
		return keyWords;
	}

	public void setKeyWords(String keyWords) {
		this.keyWords = keyWords;
	}

	public int getOffset() {
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	public int getSecondId() {
		return secondId;
	}

	public void setSecondId(int secondId) {
		this.secondId = secondId;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public GoodsDAO getGoodsDAO() {
		return goodsDAO;
	}

	public void setGoodsDAO(GoodsDAO goodsDAO) {
		this.goodsDAO = goodsDAO;
	}
	
	/**
	 * 显示主页所有最新商品列表(方法弃用)
	 * 存到request的goodsList中
	 * @return
	 */
	public String showNewGoods(){
		List goodsList=null;
		if(goodsDAO!=null)
		{
		
			goodsList=goodsDAO.findAll();
			Goods goods;
			//picurl
			String picUrl;
			
			for(int i=0;i<goodsList.size();i++)
			{
				picUrl=FileUtil.getUrl(((Goods)goodsList.get(i)).getPic());
				((Goods)goodsList.get(i)).setPic(picUrl);
			}
			//picurl
			ServletActionContext.getRequest().setAttribute("goodsList", goodsList);
		
		
		}
		return "showNewGoodsSuccess";
	}
	
	/**
	 * 显示最新商品列表,用于查找第一页之后页面商品
	 * 存到request的goodsList中
	 * 总记录数存到request的totalSize中
	 * @return
	 */
	public String showNewGoodsInPage(){
		List goodsList=null;
		
		if(goodsDAO!=null)
		{
			int offset=Integer.valueOf((String)(ServletActionContext.getRequest().getParameter("pager.offset")==null?"0":ServletActionContext.getRequest().getParameter("pager.offset")));
				
			goodsList=goodsDAO.findAllScope("0",offset, 20);//offset 从0开始
			
			ServletActionContext.getRequest().setAttribute("goodsList", goodsList);
			ServletActionContext.getRequest().setAttribute("totalSize", goodsDAO.findAll().size());
		
		}
		return "showNewGoodsInPageSuccess";
	}
	
	
	
	/**
	 * 显示最新求购商品列表,用于查找第一页之后页面商品
	 * 存到request的goodsList中
	 * 总记录数存到request的totalSize中
	 * @return
	 */
	public String showBuyNewGoodsInPage(){
		List goodsList=null;
		if(goodsDAO!=null)
		{
		
			int offset=Integer.valueOf((String)(ServletActionContext.getRequest().getParameter("pager.offset")==null?"0":ServletActionContext.getRequest().getParameter("pager.offset")));
				
			goodsList=goodsDAO.findAllScope("2",offset, 20);//offset 从0开始
			
			ServletActionContext.getRequest().setAttribute("goodsList", goodsList);
			ServletActionContext.getRequest().setAttribute("totalSize", goodsDAO.findByType("2").size());
		}
		return "showBuyNewGoodsInPageSuccess";
	}
	
	/**
	 * 显示最新卖出商品列表,用于查找第一页之后页面商品
	 * 存到request的goodsList中
	 * 总记录数存到request的totalSize中
	 * @return
	 */
	public String showSaleNewGoodsInPage(){
		List goodsList=null;
		if(goodsDAO!=null)
		{
		
			int offset=Integer.valueOf((String)(ServletActionContext.getRequest().getParameter("pager.offset")==null?"0":ServletActionContext.getRequest().getParameter("pager.offset")));
				
			goodsList=goodsDAO.findAllScope("1",offset, 20);//offset 从0开始
			
			ServletActionContext.getRequest().setAttribute("goodsList", goodsList);
			ServletActionContext.getRequest().setAttribute("totalSize", goodsDAO.findByType("1").size());
		}
		return "showSaleNewGoodsInPageSuccess";
	}
	
	/**
	 * 显示最新商品列表,用于查找第一页商品
	 * 存到request的goodsList中
	 * 总记录数存到request的totalSize中
	 * @return
	 */
	public String showNewGoodsInIndex(){
		List goodsList=null;
		if(goodsDAO!=null)
		{			
			goodsList=goodsDAO.findAllScope(type,0, 20);//offset 从0开始
			
			ServletActionContext.getRequest().setAttribute("goodsList", goodsList);
			ServletActionContext.getRequest().setAttribute("totalSize", goodsDAO.findAll().size());
		
		}
		return "showNewGoodsInIndexSuccess";
	}
	
	/**
	 * 显示最热商品列表
	 * 存到request的hotGoodsList中
	 * @return
	 */
	public String showHotGoods(){
		List goodsList=null;
		if(goodsDAO!=null)
		{
			goodsList=goodsDAO.findHotList(6);//查6条记录
			ServletActionContext.getRequest().setAttribute("hotGoodsList", goodsList);
		}
		return "showNewGoodsSuccess";
	}
	
	/**
	 * 显示一个商品具体信息
	 * @return
	 */
	public String showGoods(){
		Goods goods;
		if(goodsDAO!=null)
		{
			goods=goodsDAO.findById(id);
			goods.setHot(goods.getHot()+1);// 点击后热度加1
			goodsDAO.update(goods);
			ServletActionContext.getRequest().setAttribute("goods", goods);
		}
		return "showGoodsSuccess";
	}
	
	/**
	 * 根据二级分类显示商品
	 * 存到request的goodsList中
	 * 总记录数存到request的totalSize中
	 * @return
	 */
	public String showBySecondId(){
		List list=null;
		if(goodsDAO!=null)
		{
			list=goodsDAO.findBySecondId(secondId);
			ServletActionContext.getRequest().setAttribute("totalSize", list.size());			
			ServletActionContext.getRequest().setAttribute("goodsList", list);
		}
		return "showBySecondIdSuccess";
	}
	
	/**
	 * 搜索结果显示
	 */
	public String searchInIndex(){
		List list=null;
		if(goodsDAO!=null)
		{
			list=goodsDAO.findByTitle(keyWords, 0, 20);	//每页20条
			ServletActionContext.getRequest().setAttribute("totalSize", goodsDAO.findByTitleCount(keyWords));			
			ServletActionContext.getRequest().setAttribute("goodsList", list);
		}
		return "searchInIndexSuccess";
	}
	
	/**
	 * 添加新商品
	 * @return
	 */
	public String addNewGoods(){
			
			List list=null;

			goods.setUser((User) ServletActionContext.getContext().getSession().get("user"));
			goods.setHot(0);
			goods.setPic("goodspic.jpg");//上传图片
			goods.setPublishTime(new Timestamp(new Date().getTime()));
			goods.setSecondClass(secondClassDAO.findById(secondId));
			goods.setState("1");
			
			
			
			if(picFile!=null)
			{
			if(!ALLOWED_PIC_TYPE.contains(picFileContentType.substring(picFileContentType.indexOf('/')+1)))//检查文件格式
			{
				errorMsg="文件格式不正确！允许文件类型：jpg,jpeg,bmp,png,gif";
				return ERROR;
			}
			
			
			String picPath = ServletActionContext.getServletContext().getRealPath("/pic");
			try {
				//上传图片
				FileInputStream  is = new FileInputStream(picFile);
				
				String newName = String.valueOf(System.currentTimeMillis()+picFile.length())+picFileFileName.substring(picFileFileName.lastIndexOf('.'));
			//	File file = new File(picPath,newName);
				
				
				//OutputStream os = new FileOutputStream(file);
				byte[] fileBytes = new byte[(int) picFile.length()];
				is.read(fileBytes);
				FileUtil.write(newName, fileBytes);
				System.out.println("tmp:"+FileUtil.getLocalDir());
				System.out.println("url:"+FileUtil.getUrl(newName));
				
		/*		byte[] buffer = new byte[1024];
				int length=0;
				
				while((length= is.read(buffer)) > 0 )
				{
					os.write(buffer,0,length);
				}
				*/
				is.close();
			//	os.close();
				
				goods.setPic(newName);
			} catch (FileNotFoundException e) {
				errorMsg="未找到上传图片！";
				e.printStackTrace();
			} catch (IOException e) {
				errorMsg="上传图片失败！";
			}
			}
			
			if(goodsDAO!=null && goods!=null)
			{
				goodsDAO.save(goods);
				ServletActionContext.getRequest().setAttribute("totalSize", goodsDAO.findByTitleCount(keyWords));			
				ServletActionContext.getRequest().setAttribute("goodsList", list);
			}
			return "addNewGoodsSuccess";
		}
		
		public String deleteGoodsById()
		{
			
			Goods goods =goodsDAO.findById(id);
			if(goods == null){
				errorMsg="指定商品不存在";
				return ERROR;
				//return NONE;
			}
			PrintWriter out;
			try {
				goodsDAO.delete(goodsDAO.findById(id));
				errorMsg="success";
		/*		HttpServletResponse response = ServletActionContext.getResponse();
				response.setContentType("text/html");
				response.setCharacterEncoding("UTF-8");
				 out = response.getWriter();
				out.println("{'errorMsg':'"+errorMsg+"'}");
		*/
			} catch (Exception e) {

				errorMsg="删除商品失败，请稍后重试";
				e.printStackTrace();
				//return NONE;
				return ERROR;
				// TODO Auto-generated catch block
				
			}			
		//	out.flush();
		//	out.close();
			//return NONE;
			return "deleteGoodsByIdSuccess";
		}
	
		/**
		 * 查找id为userId的用户发布的商品记录，用于第一页显示
		 * @return
		 */
		public String showGoodsByUserIdIndex()
		{
			int totalSize = goodsDAO.findByUserId(userId).size();
			List goodsList = goodsDAO.findByUserId(userId,0,5);//从第一条记录开始，查找10条记录
			ServletActionContext.getRequest().setAttribute("goodsList", goodsList);
			ServletActionContext.getRequest().setAttribute("totalSize", totalSize);
			
			return Action.NONE;
		}
		
		/**
		 * 查找id为userId的用户发布的商品记录，用于第一页之后页面显示
		 * @return
		 */
		public String showGoodsByUserIdInPage()
		{
			int offset = ServletActionContext.getRequest().getParameter("pager.offset")==null?0:Integer.valueOf(ServletActionContext.getRequest().getParameter("pager.offset"));
			int totalSize = goodsDAO.findByUserId(userId).size();
			List goodsList = goodsDAO.findByUserId(userId,offset,5);//从第一条记录开始，查找10条记录
			ServletActionContext.getRequest().setAttribute("goodsList", goodsList);
			ServletActionContext.getRequest().setAttribute("totalSize", totalSize);
			ServletActionContext.getRequest().setAttribute("isIndex", true);
			
			return "showGoodsByUserIdInPageSuccess";
		}
		
		
}
